﻿AjaxControlToolkit.BehaviorBase.MvcAjaxHandleSubmit = function(form, evt, ajaxOptions) {
    var _onBegin = ajaxOptions.onBegin;
    ajaxOptions.onBegin = function(ajaxContext) {
        // Sys.WebForms.BeginRequestEventArgs not currently supported
        var args = new Sys.EventArgs();
        AjaxControlToolkit.BehaviorBase.ForEach(function(component) {
            component._partialUpdateBeginRequest(null, args);
        });
        if (_onBegin)
            return _onBegin(ajaxContext);
        else
            return true;
    }
    var _onSuccess = ajaxOptions.onSuccess;
    ajaxOptions.onSuccess = function(ajaxContext) {
        var dataItems = null;
        var dataItemsField = $get("__Lilium_SDI", ajaxContext.get_updateTarget());
        if (dataItemsField && dataItemsField.value)
            dataItems = eval("(" + dataItemsField.value + ")");
        else
            dataItems = new Array();
        // Sys.WebForms.BeginRequestEventArgs not currently supported
        var args = new Sys.EventArgs();
        args.get_dataItems = function() {
            return dataItems;
        }
        AjaxControlToolkit.BehaviorBase.ForEach(function(component) {
            component._partialUpdateEndRequest(null, args);
        });
        if (_onSuccess)
            return _onSuccess(ajaxContext);
        else
            return true;
    }
    var _onFailure = ajaxOptions.onFailure;
    ajaxOptions.onFailure = function(ajaxContext) {
        // Sys.WebForms.BeginRequestEventArgs not currently supported
        var args = new Sys.EventArgs();
        var dataItems = new Array();
        args.get_dataItems = function() {
            return dataItems;
        }
        AjaxControlToolkit.BehaviorBase.ForEach(function(component) {
            component._partialUpdateEndRequest(null, args);
        });
        if (_onFailure)
            return _onFailure(ajaxContext);
        else
            return true;
    }
    AjaxControlToolkit.BehaviorBase._mvcAjaxHandleSubmit(form, evt, ajaxOptions)
}

AjaxControlToolkit.BehaviorBase.ForEach = function(action) {
    var components = Sys.Application.getComponents();
    for (var i = 0; i < components.length; i++) {
        var component = components[i];
        if (AjaxControlToolkit.BehaviorBase.isInstanceOfType(component)) {
            action(component);
        }
    }
}

AjaxControlToolkit.BehaviorBase.HookMvcAjaxEvents = function() {
    if ((typeof (Sys.Mvc.AsyncForm.handleSubmit) == 'function') && !AjaxControlToolkit.BehaviorBase._mvcAjaxHandleSubmit) {
        AjaxControlToolkit.BehaviorBase._mvcAjaxHandleSubmit = Sys.Mvc.AsyncForm.handleSubmit;
        Sys.Mvc.AsyncForm.handleSubmit = AjaxControlToolkit.BehaviorBase.MvcAjaxHandleSubmit;
    }
}

Sys.Application.add_init(AjaxControlToolkit.BehaviorBase.HookMvcAjaxEvents);